<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in artCateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="screenArticle"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="screenR"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          @click="addVisible = true"
          size="small"
          class="btn-pub"
          >发表文章</el-button
        >
        <!-- 文章发布弹出层 -->
        <el-dialog
          title="发布文章"
          :visible.sync="addVisible"
          width="30%"
          :before-close="handleClose"
          fullscreen
        >
          <!-- 表单 -->
          <el-form
            ref="articleFrom"
            :model="articleFrom"
            :rules="articleRules"
            label-width="80px"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="articleFrom.title"></el-input>
            </el-form-item>
            <el-form-item label="文章类别" prop="cate_id">
              <el-select
                v-model="articleFrom.cate_id"
                placeholder="请选文章类别"
                style="width: 100%"
              >
                <el-option
                  v-for="item in artCateList"
                  :key="item.id"
                  :label="item.cate_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
              <!-- 使用 v-model 进行双向的数据绑定 -->
              <quill-editor v-model="articleFrom.content"></quill-editor>
            </el-form-item>
            <el-form-item label="文章封面" prop="cover_img">
              <!-- 用来显示封面的图片 -->
              <img
                v-if="!coverImg"
                src="../../../assets/images/cover.jpg"
                alt=""
                class="cover-img"
                ref="imgRef"
              />
              <img
                v-else
                :src="coverImg"
                alt=""
                class="cover-img"
                ref="imgRef"
              />
              <br />
              <!-- 文件选择框，默认被隐藏 -->
              <input
                @change="changeImg"
                type="file"
                style="display: none"
                accept="image/*"
                ref="iptFile"
              />
              <!-- 选择封面的按钮 -->
              <el-button type="text" @click="$refs.iptFile.click()"
                >+ 选择封面</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="!publishedButton"
                icon="el-icon-document-checked"
                type="primary"
                @click="publishedArticles('已发布')"
                round
                >发布文章</el-button
              >
              <el-button v-else type="primary" :loading="true"
                >发布中</el-button
              >
              <el-button
                icon="el-icon-edit"
                type="info"
                @click="publishedArticles('草稿')"
                round
                >存为草稿</el-button
              >
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="articleList" border style="width: 100%">
        <el-table-column label="文章标题">
          <template v-slot="{ row }">
            <el-link @click="lookVisible = true ,getArticleInfo(row.id)" type="primary">
              <i class="el-icon-view el-icon--right"></i> {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类" width="180">
        </el-table-column>
        <el-table-column label="发表时间">
          {{ fromDate(articleList.pub_date) }}
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作" width="65">
          <template v-slot="{ row }">
            <el-button
              type="danger"
              @click="delArticle(row.id)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="预览"
        :visible.sync="lookVisible"
        width="30%"
        fullscreen
      >
      <div class="articleBox">
        <h1> {{articleInfo.title}} </h1>
         <el-divider content-position="left">分类：{{articleInfo.cate_name}}</el-divider>
        <el-divider>作者：{{articleInfo.nickname||articleInfo.username}}</el-divider>
        <el-divider content-position="right">发布时间：{{fromDate(articleInfo.pub_date)}}</el-divider>
        <el-divider content-position="right">发布状态：{{articleInfo.state}}</el-divider>
        <el-image style="width: 600px; height:400px"  :src="'http://www.liulongbin.top:3008'+articleInfo.cover_img"
        :preview-src-list="['http://www.liulongbin.top:3008'+articleInfo.cover_img]">
  </el-image>
        <div class="contentBox" v-html="articleInfo.content">
        </div>
        </div>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'

export default {
  name: 'ArtList',
  data () {
    return {
      addVisible: false,
      lookVisible: false,
      publishedButton: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      articleFrom: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      articleInfo: {},
      coverImg: '',
      articleRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { pattern: /^\S{1,30}$/, message: '1-30 个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'change' },
          { pattern: /\S/, message: '非空的字符串', trigger: 'change' }
        ],
        cover_img: [
          { required: true, message: '请选择文章封面', trigger: 'change' }
        ]
      },
      screenList: {},
      articleList: [],
      total: 0
    }
  },
  created () {
    this.getArticleList()
  },
  computed: {
    ...mapState('article', ['artCateList'])
  },
  methods: {
    async getArticleList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.articleList = res.data
      this.total = res.total
    },
    fromDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    async delArticle (id) {
      // console.log(id)
      const result = await this.$confirm('确认删除？', '警告!').catch((e) => e)
      // console.log(result)
      if (result === 'confirm') {
        const { data: res } = await this.$http.delete('/my/article/info', {
          params: { id }
        })
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.total < 2) return this.getArticleList()
        if (this.articleList.length < 2) this.q.pagenum--
        this.getArticleList()
      } else {
        this.$message.success('取消删除成功')
      }
    },
    handleSizeChange (val) {
      this.screenR()
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.getArticleList()
    },
    handleCurrentChange (val) {
      this.screenR()
      this.q.pagenum = val
      this.getArticleList()
    },
    async screenArticle () {
      this.screenList = this.q
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.screenList
      })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.articleList = res.data
      this.total = res.total
    },
    screenR () {
      this.q.cate_id = ''
      this.q.state = ''
      this.getArticleList()
    },
    handleClose (done) {
      this.$confirm('确认关闭吗，文章尚未保存？', '提示')
        .then((_) => {
          this.$refs.articleFrom.resetFields()
          this.coverImg = ''
          done()
        })
        .catch((_) => {})
    },
    changeImg (e) {
      // console.log(e.target.files)
      if (e.target.files.length === 0) { return this.$message.error('请选择封面图片') }
      this.articleFrom.cover_img = e.target.files[0]
      this.coverImg = URL.createObjectURL(e.target.files[0])
    },
    publishedArticles (val) {
      this.articleFrom.state = val
      this.$refs.articleFrom.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写')
        const fd = new FormData()
        Object.keys(this.articleFrom).forEach((key) => {
          fd.append(key, this.articleFrom[key])
        })
        this.publishedButton = true
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.addVisible = false
        this.$refs.articleFrom.resetFields()
        this.coverImg = ''
        this.publishedButton = false
        this.getArticleList()
      })
    },
    async getArticleInfo (id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      // console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.articleInfo = res.data
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
/deep/ .ql-editor {
  min-height: 300px;
}
.articleBox {
  h1{
    font-size: 50px;
    text-align: center;
  }

}
</style>
